package com.shan.thread;

/**
 * description
 * 暂停当前正在执行的线程对象，并执行其他线程
 *
 * @author shanzheng <br/>
 * @date 16:14 2019/1/16.<br/>
 * Modified By <br/>
 */
public class YieldThreadDemo {
    public static void main(String[] args) {
        YieldThread yieldThread1 = new YieldThread();
        YieldThread yieldThread2 = new YieldThread();
        Thread thread1 = new Thread(yieldThread1, "线程A");
        Thread thread2 = new Thread(yieldThread2, "线程B");
        thread1.start();
        thread2.start();
    }
}

class YieldThread implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {

            }
            System.out.println(Thread.currentThread().getName() + "运行" + i);
            if (i == 2) {
                System.out.print("线程礼让：");
                // 将目前正在执行的线程暂停，允许其它线程执行
                Thread.yield();
            }

        }
    }
}